<template>
  <HeaderComponent/>
  <div id="BackLink">
    <router-link :to="{name:'Main'}">Return to Main Menu</router-link>
  </div>

  <div id="Catalog">
    <form @submit.prevent="handleSubmit">
      <p v-if="signOnMsg" style="color:red;">{{ signOnMsg }}</p>

      <h3>User Information</h3>
      <h4>密码至少为8位，且同时包含数字和字母</h4>

      <table style="width: 40%; margin: 0 auto;">
        <tr>
          <td>Username:</td>
          <td>
            <input
              id="username"
              type="text"
              v-model="form.username"
              @blur="checkAccount"
              placeholder="Enter your username"
            />
            <span id="isAccountExist">{{ usernameCheck }}</span>
          </td>
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <input
              id="password"
              type="password"
              v-model="form.password"
              @blur="checkCode"
              placeholder="Enter password"
            />
            <span id="isProperCode">{{ passwordCheck }}</span>
          </td>
        </tr>
        <tr>
          <td>Repeat Password:</td>
          <td>
            <input
              id="repeatedPassword"
              type="password"
              v-model="form.repeatPassword"
              @blur="checkRepeatedCode"
              placeholder="Repeat password"
            />
            <span id="isRepeatedCode">{{ repeatCheck }}</span>
          </td>
        </tr>
      </table>

      <!-- 引入额外账户字段 -->
      <AccountForm v-model="form" />

      <!-- <p>
        Verification:
        <input type="text" v-model="form.verificationCode" />
        <img :src="captchaUrl" @click="refreshCaptcha" style="cursor: pointer;" />
      </p> -->

      <input type="submit" value="Save Account Information" />
    </form>
  </div>
  <br><br><br><br><br>
  <FooterComponent/>
  
</template>
  
<script setup>
  import { ref } from 'vue';
  import { useRouter } from 'vue-router';
  import HeaderComponent from '@/components/Header.vue';
  import FooterComponent from '@/components/Footer.vue';
  import AccountForm from '@/components/account/AccountForm.vue';
  import { register } from '@/api/account.js'; // 引入 register 方法

  
  const router = useRouter();
  
  const signOnMsg = ref('');
  const form = ref({
    username: '',
    password: '',
    repeatPassword: '',
    email: '',
    firstName: '',
    lastName: '',
    status: 'OK',
    address1: '',
    address2: '',
    city: '',
    state: '',
    zip: '',
    country: '',
    phone: '',
    langpref: 'english',
    favcategory: 'MAIN',
    mylistopt: 1,
    banneropt: 1,
    verificationCode: '',
  });

  // 验证状态
  const usernameCheck = ref('');
  const passwordCheck = ref('');
  const repeatCheck = ref('');
  const captchaUrl = ref('');

  // 验证函数
  function checkAccount() {
    usernameCheck.value = form.value.username ? 'OK' : '用户名不能为空';
  }

  function checkCode() {
    const pwd = form.value.password;
    const valid = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
    passwordCheck.value = valid.test(pwd) ? 'OK' : '密码需至少8位并包含数字和字母';
  }

  function checkRepeatedCode() {
    repeatCheck.value = form.value.repeatPassword === form.value.password ? 'OK' : '密码不一致';
  }

  // function refreshCaptcha() {
  //   // 这里添加刷新验证码的逻辑
  //   console.log('刷新验证码');
  // }

  async function handleSubmit() {
    // 检查所有必填字段
    if (!form.value.username || !form.value.password || !form.value.email || !form.value.phone) {
      signOnMsg.value = '请填写所有必填字段';
      return;
    }

    // 检查密码验证
    if (
      usernameCheck.value === 'OK' &&
      passwordCheck.value === 'OK' &&
      repeatCheck.value === 'OK'
    ) {
      try {
        const response = await register({
          username: form.value.username,
          password: form.value.password,
          email: form.value.email,
          firstName: form.value.firstName,
          lastName: form.value.lastName,
          status: form.value.status,
          address1: form.value.address1,
          address2: form.value.address2,
          city: form.value.city,
          state: form.value.state,
          zip: form.value.zip,
          country: form.value.country,
          phone: form.value.phone,
          langpref: form.value.langpref,
          favcategory: form.value.favcategory,
          mylistopt: form.value.mylistopt,
          banneropt: form.value.banneropt
        });
        console.log('注册提交的数据：', response);
        if (response.status === 0) {
          console.log('注册成功！');
          router.push('/signon'); // 注册成功后跳转到登录页
        } else {
          signOnMsg.value = response.message || '注册失败';
        }
      } catch (error) {
        console.error('异常捕获：',error);
        signOnMsg.value = error.response?.message || '注册失败，请稍后再试';
      }
    } else {
      signOnMsg.value = '请完善所有必填信息';
    }
  }
</script>
  
<style scoped>
  input[type="text"],
  input[type="password"],
  input[type="email"] {
    width: 100%;
    max-width: 120px;
    padding: 6px 10px;
    margin: 6px 0;
    font-size: 14px;
    border: 1.5px solid #a87c5a;
    border-radius: 5px;
    background-color: #fffdfa;
    color: #734012;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: border-color 0.2s ease, box-shadow 0.2s ease;
  }

  input[type="text"]:focus,
  input[type="password"]:focus,
  input[type="email"]:focus {
    outline: none;
    border-color: #fccc1c;
    background-color: #fffef4;
    box-shadow: 0 2px 5px rgba(252, 204, 28, 0.15);
  }

  input[type="text"]::placeholder,
  input[type="password"]::placeholder,
  input[type="email"]::placeholder {
    color: #b28e73;
    font-style: italic;
    opacity: 0.8;
  }

  span {
    color: #e74c3c;
    font-size: 12px;
    margin-left: 10px;
  }

  table {
    border-spacing: 0 10px;
  }

  td {
    padding: 5px;
  }

  td:first-child {
    text-align: right;
    padding-right: 15px;
  }

  input[type="submit"] {
    background-color: #f1c48f;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    margin-top: 20px;
    width: auto;
    max-width: none;
  }

  input[type="submit"]:hover {
    background-color: #fcdc5e;
  }

  #BackLink {
    margin: 20px;
  }

  #BackLink a {
    color: #734012;
    text-decoration: none;
  }

  #BackLink a:hover {
    color: #fccc1c;
  }

  h3 {
    color: #734012;
    margin: 20px 0;
  }

  h4 {
    color: #b28e73;
    font-style: italic;
    margin: 10px 0;
  }
</style>
  